package com.mrjy.maintain.bo;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.mrjy.common.dto.CardListDto;
import com.mrjy.common.dto.SMSSendDto;
import com.mrjy.common.entity.CoursePackageInfo;
import com.mrjy.common.entity.CoursePackageVip;
import com.mrjy.common.entity.IntegralInfo;
import com.mrjy.common.entity.MessageInfo;
import com.mrjy.common.entity.SMSSendInfo;
import com.mrjy.common.entity.SMSSendReqInfo;
import com.mrjy.common.entity.SalesCardInfo;
import com.mrjy.common.entity.UserBalancePayment;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.UserMemberInfo;
import com.mrjy.common.redis.RedisPool;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.ExportExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.MD5Encrypt;
import com.mrjy.common.util.RandomUtil;
import com.mrjy.common.util.RedisUtil;
import com.mrjy.common.util.RegexUtil;
import com.mrjy.common.util.ResponseCode;
import com.mrjy.common.util.SMSTemplate;
import com.mrjy.common.util.SMSUtil;
import com.mrjy.coursepackage.dao.ICoursePackageInfoDao;
import com.mrjy.coursepackage.dao.ICoursePackageVipDao;
import com.mrjy.coursepackage.dto.CoursePackageInfoDTO;
import com.mrjy.integral.util.IntegralEnum;
import com.mrjy.integral.util.IntegralUtil;
import com.mrjy.maintain.dao.IMessageInfoDao;
import com.mrjy.maintain.dao.ISMSSendInfoDao;
import com.mrjy.maintain.dao.ISalesCardInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.maintain.dao.IUserMemberInfoDao;
import com.mrjy.maintain.util.RoleInfoEnum;
import com.mrjy.payment.dao.IUserBalancePaymentDao;
import com.mrjy.wechat.conts.WxConsts;
import com.mrjy.wechat.util.WeChatUtil;

@Service("salesCardInfoBo")
public class SalesCardInfoBo implements ISalesCardInfoBo {

	@Resource
	private ISalesCardInfoDao salesCardDao;
	
	@Resource
	private ISMSSendInfoDao smsSendInfoDao;
	
	@Resource
	private IUserInfoDao userDao;
	
	@Resource
	private IUserMemberInfoDao memberDao;
	@Resource
	private IUserBalancePaymentDao paymentDao;
	
	@Resource
	private IMessageInfoDao messageInfoDao;
	
	@Resource
	private ICoursePackageVipDao coursePackageVipDao;
	
	@Resource
	private ICoursePackageInfoDao coursePackageInfoDao;
	
	@Resource
	private RedisPool redisPool;
	
	
	private Logger logger = LoggerFactory.getLogger(SalesCardInfoBo.class);

    private org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(SalesCardInfoBo.class);

    @Override
	public SalesCardInfo queryById(int id,UserInfo userInfo) {
		if (userInfo == null) {
			return null;
		}
		return salesCardDao.queryById(id);
	}
	
	@Override
	public Map<String, Object> activateSaleCard(SalesCardInfo salesCardInfo,
			SMSSendInfo smsSendInfo) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(smsSendInfo.getRecNum()) && StringUtils.isNotBlank(smsSendInfo.getSendCode())) {
			smsSendInfo.setSmsCode("SMS_16440022");
			SMSSendInfo smsSendInfoDB = smsSendInfoDao.validateSMSCode(smsSendInfo);
			if (smsSendInfoDB == null) {
				resultMap.put("status", "error");
				resultMap.put("content", "您输入的短信验证码有误!");
			} else if (smsSendInfoDB.getSmsSendTime().getTime() + 600000 < new Date()
					.getTime()) {
				resultMap.put("status", "error");
				resultMap.put("content", "您输入的短信验证码已过期，请重发!");
			}else {
				//smsSendInfo.setSmsStatus("2");
				//smsSendInfoDao.updateStatusSelective(smsSendInfo);
				if (StringUtils.isNotBlank(salesCardInfo.getActivationCode())) {
					//查询激活卡
					SalesCardInfo existCard = salesCardDao.queryByActivationCode(salesCardInfo.getActivationCode());
					if (existCard != null && (existCard.getActivationCode()).equalsIgnoreCase(salesCardInfo.getActivationCode())) {
						if (existCard.getActivationStatus().intValue()==1) {
							resultMap.put("status", "error");
							resultMap.put("content", "该卡已被激活!");
							return resultMap;
						}else if (existCard.getExpiryDate()<new Date().getTime() || existCard.getDisableFlag() ==1) {
							resultMap.put("status", "error");
							resultMap.put("content", "该卡已失效!");
							return resultMap;
						}
						
						UserInfo existUser = userDao.queryByMobilePhone(smsSendInfo.getRecNum());
						//不存在时创建新用户并插入
						if(existUser==null){
							existUser = new UserInfo();
							existUser.setLoginCode(smsSendInfo.getRecNum()+"_"+RandomUtil.generateString2(3));
							String newPassword=RandomUtil.generateNumChar(6);
							existUser.setPassword(MD5Encrypt.encryptByMD5(newPassword));
							existUser.setRoleId(RoleInfoEnum.STUDENT.getRoleId());
							existUser.setRegisterDate(new Date().getTime());
							existUser.setDisableFlag(0);
							if (StringUtils.isNotBlank(salesCardInfo.getUserName())) {
								existUser.setUserName(salesCardInfo.getUserName());
							}else{
								existUser.setUserName("新用户");
							}
							existUser.setMobilePhone(smsSendInfo.getRecNum());
							userDao.insertSelective(existUser);
							existUser = userDao.queryByMobilePhone(smsSendInfo.getRecNum());
							
							//发送账号和密码短信
							SMSSendDto smsSendDto=new SMSSendDto();
							smsSendDto.setRecNum(smsSendInfo.getRecNum());
							smsSendDto.setProduct("365家长课堂");
							smsSendDto.setCode(smsSendInfo.getRecNum());
							smsSendDto.setPassword(newPassword);
							sendSMSToStudent(smsSendDto);
							resultMap.put("status", "ok");
							resultMap.put("content", "您已成功激活卡，请稍后留意短信获取账号与密码!");
						}else {
							UserBalancePayment payment = new UserBalancePayment();
							payment.setUserId(existUser.getId());
							List<UserBalancePayment> existPays = paymentDao.queryHadPaymentByUserId(payment);
							if (existPays == null || existPays.size() ==0) {
								//已注册，但没购买过会员套餐
								String newPassword=RandomUtil.generateNumChar(6);
								existUser.setPassword(MD5Encrypt.encryptByMD5(newPassword));
								if (StringUtils.isNotBlank(salesCardInfo.getUserName())) {
									existUser.setUserName(salesCardInfo.getUserName());
								}
								userDao.updateById(existUser);
								
								//发送账号和密码短信
								SMSSendDto smsSendDto=new SMSSendDto();
								smsSendDto.setRecNum(smsSendInfo.getRecNum());
								smsSendDto.setProduct("365家长课堂");
								smsSendDto.setCode(smsSendInfo.getRecNum());
								smsSendDto.setPassword(newPassword);
								sendSMSToStudent(smsSendDto);
								resultMap.put("status", "ok");
								resultMap.put("content", "您已成功激活卡，请稍后留意短信获取账号与密码!");
							}else {
								resultMap.put("status", "ok");
								resultMap.put("content", "您已成功激活卡，请前去登录!");	
							}
						}
						
						//发送激活成功短信
						SMSSendDto activationSms=new SMSSendDto();
						activationSms.setRecNum(smsSendInfo.getRecNum());
						activationSms.setName("365家长课堂会员");
						activationSms.setCode(smsSendInfo.getRecNum());
						sendActivationSMS(activationSms);
						
						//标注已激活卡
						existCard.setUserId(existUser.getId());
						existCard.setActivationStatus(1);
						existCard.setActivationDate(new Date().getTime());
						salesCardDao.updateSalesCard(existCard);
						
						//充值并开通会员
						UserBalancePayment payment = new UserBalancePayment();
						payment.setName(existCard.getSalesCardName());
						payment.setStatusId(2);
						payment.setMoney(365f);
						payment.setUserId(existUser.getId());
						payment.setCode(existCard.getActivationCode());
						payment.setOrderTime(new Date());
						payment.setCompleteTime(new Date());
						payment.setPaymentMethod("card");
						payment.setTypeId(3);
						paymentDao.insertCardOrder(payment);
					}else {
						resultMap.put("status", "error");
						resultMap.put("content", "您输入的激活密码有误!");
					}
				}else {
					resultMap.put("status", "error");
					resultMap.put("content", "您输入的激活密码有误!");
				}	
			}
		} else {
			resultMap.put("status", "error");
			resultMap.put("content", "信息输入有误，请重输!");
		}
		return resultMap;
	}

	/**
	 * 发送短信通知
	 */
	private void sendSMSToStudent(SMSSendDto smsSendDto){
		String uniqueFlag = "";
		if (smsSendDto.getUniqueFlag() != null) {
			uniqueFlag = smsSendDto.getUniqueFlag();
		}
		String smsType = "normal";
		String smsFreeSignName = SMSUtil.SIGN_NAME[0];
		SMSTemplate sms = SMSTemplate.TEMPLATE_02;	
		Map<String, Object> smsParamMap = new HashMap<String, Object>();		
		smsParamMap.put("name", smsSendDto.getProduct());
		smsParamMap.put("code", smsSendDto.getCode());
		smsParamMap.put("passwod",smsSendDto.getPassword());	
		SMSSendReqInfo smsSendReq = new SMSSendReqInfo(smsType,
				smsFreeSignName, smsParamMap, smsSendDto.getRecNum(), sms);

		Map<String, Object> map = SMSUtil.sendSMS(smsSendReq);
		if (map.get("responseCode") == ResponseCode.SUCCESS.getCode()) {
			
			// 插入一条信息记录
			JSONObject jsonObject = JSONObject.fromObject(map
					.get("responseDesc"));
			jsonObject = JSONObject.fromObject(jsonObject
					.getString("alibaba_aliqin_fc_sms_num_send_response"));
			jsonObject = JSONObject.fromObject(jsonObject.getString("result"));				
			SMSSendInfo smsSendInfo = new SMSSendInfo(); 
			smsSendInfo.setSmsCode(sms.getTemplateID());
			smsSendInfo.setRecNum(smsSendDto.getRecNum());
			smsSendInfo.setSendCode(smsSendDto.getCode());
			smsSendInfo.setUniqueFlag(uniqueFlag);
			try {
				SimpleDateFormat sim = new SimpleDateFormat(
						"yyyy-MM-dd hh:mm:ss");
				String dateStr = DateUtil.dateToString(new Date(),
						DateUtil.FULL_DATE);
				Date smsSendTime = sim.parse(dateStr);
				smsSendInfo.setSmsSendTime(smsSendTime);
			} catch (ParseException e) {
				e.printStackTrace();
			}			
			smsSendInfo.setSmsStatus("2");
			smsSendInfo.setSmsCode("SMS_16440023");
			smsSendInfo.setBizCode(jsonObject.getString("model"));
			smsSendInfoDao.insert(smsSendInfo);
		}
	}
	
	/**
	 * 发送激活福卡成功短信通知
	 * smsSendDto:name,code,
	 */
	private void sendActivationSMS(SMSSendDto smsSendDto){
		String uniqueFlag = "";
		if (smsSendDto.getUniqueFlag() != null) {
			uniqueFlag = smsSendDto.getUniqueFlag();
		}
		String smsType = "normal";
		String smsFreeSignName = SMSUtil.SIGN_NAME[0];
		SMSTemplate sms = SMSTemplate.TEMPLATE_04;	
		Map<String, Object> smsParamMap = new HashMap<String, Object>();
		smsParamMap.put("name", smsSendDto.getName());
		smsParamMap.put("code", smsSendDto.getCode());
		SMSSendReqInfo smsSendReq = new SMSSendReqInfo(smsType,
				smsFreeSignName, smsParamMap, smsSendDto.getRecNum(), sms);

		Map<String, Object> map = SMSUtil.sendSMS(smsSendReq);
		if (map.get("responseCode") == ResponseCode.SUCCESS.getCode()) {
			
			// 插入一条信息记录
			JSONObject jsonObject = JSONObject.fromObject(map
					.get("responseDesc"));
			jsonObject = JSONObject.fromObject(jsonObject
					.getString("alibaba_aliqin_fc_sms_num_send_response"));
			jsonObject = JSONObject.fromObject(jsonObject.getString("result"));				
			SMSSendInfo smsSendInfo = new SMSSendInfo(); 
			smsSendInfo.setSmsCode(sms.getTemplateID());
			smsSendInfo.setRecNum(smsSendDto.getRecNum());
			smsSendInfo.setSendCode(smsSendDto.getCode());
			smsSendInfo.setUniqueFlag(uniqueFlag);
			try {
				SimpleDateFormat sim = new SimpleDateFormat(
						"yyyy-MM-dd hh:mm:ss");
				String dateStr = DateUtil.dateToString(new Date(),
						DateUtil.FULL_DATE);
				Date smsSendTime = sim.parse(dateStr);
				smsSendInfo.setSmsSendTime(smsSendTime);
			} catch (ParseException e) {
				e.printStackTrace();
			}			
			smsSendInfo.setSmsStatus("2");
//			smsSendInfo.setSmsCode("SMS_16440023");
			smsSendInfo.setBizCode(jsonObject.getString("model"));
			smsSendInfoDao.insert(smsSendInfo);
		}
	}


	@Override
	public List<SalesCardInfo> getCardStatus(){
		String[] status = {"全部","未激活","已激活"};
		List<SalesCardInfo> list = new ArrayList<SalesCardInfo>();
		for (int i=0;i<status.length;i++) {
			SalesCardInfo statusInfo = new SalesCardInfo();
			statusInfo.setId(i-1);
			statusInfo.setText(status[i]);
			list.add(statusInfo);
		}
		return list;
	}
	
	@Override
	public Map<String, Object> getCardByPageBack(SalesCardInfo cardInfo,UserInfo userInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (userInfo == null) {
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (cardInfo.getActivationStatus() != null && cardInfo.getActivationStatus().intValue() == -1) {
			cardInfo.setActivationStatus(null);
		}
		if (StringUtils.isNotBlank(cardInfo.getActivationCode())) {
			cardInfo.setActivationCode("%"+ cardInfo.getActivationCode() + "%");
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			if (StringUtils.isNotBlank(cardInfo.getStartTimeString())) {
				cardInfo.setStartTime(sdf.parse(cardInfo.getStartTimeString()).getTime());	
			}
			if (StringUtils.isNotBlank(cardInfo.getEndTimeString())) {
				cardInfo.setEndTime(sdf.parse(cardInfo.getEndTimeString()).getTime());
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		int total = salesCardDao.getTotalCardCount(cardInfo);
		if(total > 0){
			List<SalesCardInfo> cards = salesCardDao.queryCardByPage(cardInfo); 
			for (SalesCardInfo s : cards) {
				s.setAddDateString(sdf.format(new Date(s.getAddDate())));
				s.setAddDate(0);
				s.setExpiryDateString(sdf.format(new Date(s.getExpiryDate())));
				s.setExpiryDate(0);
				if(s.getActivationDate() !=0){
					s.setActivationDateString(sdf.format(new Date(s.getActivationDate())));
				}
				s.setPrice((double)s.getDays());  //福卡价格
			}
			map.put("rows", cards);
		}
		
		map.put("total", salesCardDao.getTotalCardCount(cardInfo));
		return map;
	}
	
	@Override
	public Object exportCard(SalesCardInfo cardInfo, UserInfo userInfo,HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (userInfo == null) {
			return map;
		}
		
		if (cardInfo.getActivationStatus() != null && cardInfo.getActivationStatus().intValue() == -1) {
			cardInfo.setActivationStatus(null);
		}
		if (StringUtils.isNotBlank(cardInfo.getActivationCode())) {
			cardInfo.setActivationCode("%"+ cardInfo.getActivationCode() + "%");
		}
		String startTime = "";
		String endTime = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		//获取添加时间
		try {
			if (StringUtils.isNotBlank(cardInfo.getStartTimeString())) {
				cardInfo.setStartTime(sdf.parse(cardInfo.getStartTimeString()).getTime());
				startTime = cardInfo.getStartTimeString();
			}
		} catch (ParseException e) {
			return "dataError";
		}
		try {
			if (StringUtils.isNotBlank(cardInfo.getEndTimeString())) {
				cardInfo.setEndTime(sdf.parse(cardInfo.getEndTimeString()).getTime() + 86400000);
				endTime = cardInfo.getEndTimeString();
			}
		} catch (ParseException e1) {
			return "dataError";
		}
		
		//OutputStream out = null;
		String sheetName = "销售卡导出列表";
		/*try {
			String fileName =  sheetName + "("+ startTime + "-" + endTime + ")"
					+ DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)
					+ ".xls";
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition", "attachment;fileName="
					+ new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
			out = response.getOutputStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		
		
		List<CardListDto> cards = salesCardDao.queryExportCardList(cardInfo); 
		
		String[] headers = {"销售卡名称","卡激活密码","激活状态","激活时间","激活有效期"};
		ExportExcelUtil<CardListDto> ex = new ExportExcelUtil<CardListDto>();
		//ex.exportExcel(sheetName, headers, cards, out);
		ex.commonExportExcel(sheetName, headers, cards, response, null);
		
		return "ok";
	}

	@Override
	public Object txGenerateCardBatch(SalesCardInfo salesCardInfo,UserInfo userInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (userInfo == null) {
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (salesCardInfo.getId() == null || salesCardInfo.getId().intValue() <=0 
				/*|| salesCardInfo.getId().intValue() > 200*/ || !RegexUtil.checkDigit(salesCardInfo.getId()+"")) {
			map.put("err_code", 400);
			map.put("err_msg", "福卡数量必须为1-200的数值");
			return map;
		}
		long expireDate = 0;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		//激活失效时间
		if (StringUtils.isBlank(salesCardInfo.getExpiryDateString())) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			calendar.add(Calendar.YEAR, 1);//默认过期时间一年后
			expireDate = calendar.getTime().getTime();
		}else {
			try {
				expireDate = sdf.parse(salesCardInfo.getExpiryDateString()).getTime();
			} catch (ParseException e) {
				//出错处理
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.YEAR, 1);//默认过期时间一年后
				expireDate = calendar.getTime().getTime();
			}
		}
		
		//ArrayList<SalesCardInfo> cardList = generateCard(salesCardInfo,expireDate);
		String comment = StringUtils.isBlank(salesCardInfo.getComment())?null:salesCardInfo.getComment();
		int days = salesCardInfo.getDays()==null?365:salesCardInfo.getDays();
		
		int coursePackge = 0;
		//salesCardInfo.getType() == 0 vip福卡激活，salesCardInfo.getType() == 1 课程包激活
		if(salesCardInfo.getType() == 1 && salesCardInfo.getCoursePackageId() !=null ){
			coursePackge = salesCardInfo.getCoursePackageId();
		}
		ArrayList<SalesCardInfo> cardList  = generateCard(8 ,salesCardInfo.getId() ,expireDate,days, comment,salesCardInfo.getIsFree(),salesCardInfo.getType(),coursePackge);
		int row = salesCardDao.insertCardBatch(cardList);
		if (row > 0) {
			map.put("err_code", 200);
			map.put("err_msg", "添加成功");
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "添加失败");
		}
		
		/*try {
			row = salesCardDao.insertCardBatch(cardList);
		} catch (Exception e) { 
			logger.info("批量生成激活密码失败---生成密码重复---再次进行批量生成");
			try {
				cardList = generateCard(salesCardInfo,expireDate);
				row = salesCardDao.insertCardBatch(cardList);
			} catch (Exception e1) {
				logger.info("批量生成激活密码再次失败");
				row = 0;
			}
		}*/
		return map;
	}

	//批量生成卡
	private ArrayList<SalesCardInfo> generateCard(SalesCardInfo salesCardInfo,
			long expireDate) {
		ArrayList<SalesCardInfo> cardList = new ArrayList<SalesCardInfo>();
		long addDate = new Date().getTime();
		for (int i = 0; i < salesCardInfo.getId(); i++) {
			SalesCardInfo card = new SalesCardInfo();
			card.setSalesCardName("明人福卡");
//			card.setActivationCode("MR"+RandomUtil.generateString2(4)+RandomUtil.generateUpperString(2));
//			card.setActivationCode(RandomUtil.generateUpperString2(2)+RandomUtil.generateString3(6));
			card.setActivationCode(RandomUtil.generateString2(8));
			card.setExpiryDate(expireDate);
			
			card.setAddDate(addDate);
			cardList.add(card);
		}
		return cardList;
	}
	/*
	 * 批量生成福卡激活码（纯数字）
	 * @param num 激活的位数 
	 * @param count 批量生成的记录数
	 */
	private ArrayList<SalesCardInfo> generateCard(int num , int count,long expireDate,int days,String comment,int isFree,int type, int coursePackageId){
		ArrayList<SalesCardInfo> cardList = new ArrayList<SalesCardInfo>();
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("num", num);
		map.put("count", count);
		ArrayList<String> codeList = salesCardDao.getNotRepeatActivationCode(map);
		if (null != codeList && codeList.size() > 0) {
			long addDate = new Date().getTime();
			for(String code : codeList){
				SalesCardInfo info = salesCardDao.queryByActivationCode(code);
				if(info == null){
					SalesCardInfo card = new SalesCardInfo();
					card.setSalesCardName("明人福卡");
					card.setActivationCode(code);
					card.setExpiryDate(expireDate);
					card.setAddDate(addDate);
					card.setDays(days);
					card.setIsFree(isFree);
					card.setComment(comment);
					card.setType(type);
					card.setCoursePackageId(coursePackageId);
					cardList.add(card);
				}
			}
		}
		return cardList;
	}
	/*
	 * 批量生成福卡激活码（纯数字）
	 * @param num 激活的位数 
	 * @param count 批量生成的记录数
	 */
	private ArrayList<SalesCardInfo> generateCard(int num , int count,long expireDate,int days,String comment){
		ArrayList<SalesCardInfo> cardList = new ArrayList<SalesCardInfo>();
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("num", num);
		map.put("count", count);
		ArrayList<String> codeList = salesCardDao.getNotRepeatActivationCode(map);
		if (null != codeList && codeList.size() > 0) {
			long addDate = new Date().getTime();
			for(String code : codeList){
				SalesCardInfo info = salesCardDao.queryByActivationCode(code);
				if(info == null){
					SalesCardInfo card = new SalesCardInfo();
					card.setSalesCardName("明人福卡");
					card.setActivationCode(code);
					card.setExpiryDate(expireDate);
					card.setAddDate(addDate);
					card.setDays(days);
					card.setComment(comment);
					cardList.add(card);
				}
			}
		}
		return cardList;
	}

	@Override
	public String updateSalesCard(SalesCardInfo salesCardInfo, UserInfo userInfo) {
		return null;
	}

	@Override
	public Object updateDisableFlag(SalesCardInfo salesCardInfo,
			UserInfo userInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(null == userInfo ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (salesCardInfo.getIds()==null||salesCardInfo.getIds().length==0) {
			map.put("err_code", 400);
			map.put("err_msg", "请勾选要操作的记录");
			return map;
		}
		int row =  salesCardDao.updateDisableFlag(salesCardInfo);
        if (row>0) {
        	map.put("err_code", 200);
        	map.put("err_msg", "操作成功,"+row+"条记录受影响");
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "操作失败,"+row+"条记录受影响");
		}
        return map;
		
	}

	@Override
	public Map<String, Object> txActivateSaleCard(String userName, String mobilePhone,
			String password, String validcode, String fuCardCode) {
		Map<String, Object> map = new HashMap<String, Object>();
		//
		if (StringUtils.isNotBlank(mobilePhone) && StringUtils.isNotBlank(validcode)) {
			SMSSendInfo smsSendInfo = new SMSSendInfo();
			smsSendInfo.setRecNum(mobilePhone);
			smsSendInfo.setSendCode(validcode);
			smsSendInfo.setSmsCode("SMS_16440022");
			//校验验证码
			SMSSendInfo smsSendInfoDB = smsSendInfoDao.validateSMSCode(smsSendInfo);
			if (smsSendInfoDB == null) {
				map.put("err_code", "101");
				map.put("err_msg", "您输入的短信验证码有误!");
				return map;
			}
			if (smsSendInfoDB.getSmsSendTime().getTime() + 600000 < new Date()
					.getTime()) {
				map.put("err_code", "102");
				map.put("err_msg", "您输入的短信验证码已过期，请重发!");
				return map;
			}
		}else {
			map.put("err_code", "401");
			map.put("err_msg", "输入的手机号码或验证码有误");
			return map;
		}
		
		if (StringUtils.isBlank(fuCardCode)){
			map.put("err_code", "204");
			map.put("err_msg", "您输入的激活密码为空!");
			return map;
		}
		//查询激活卡
		SalesCardInfo existCard = salesCardDao.queryByActivationCode(fuCardCode);
		if (existCard != null && (existCard.getActivationCode()).equalsIgnoreCase(fuCardCode)) {
			if (existCard.getActivationStatus().intValue()==1) {
				map.put("err_code", "201");
				map.put("err_msg", "该卡已被激活!");
				return map;
			}else if (existCard.getExpiryDate()<new Date().getTime() || existCard.getDisableFlag() ==1) {
				map.put("err_code", "202");
				map.put("err_msg", "该卡已失效!");
				return map;
			}
		}else {
			map.put("err_code", "203");
			map.put("err_msg", "您输入的激活密码有误!");
			return map;
		}	
		
		Timestamp startTime = null;
		Timestamp endTime = null;
		UserInfo existUser = userDao.queryByMobilePhone(mobilePhone);
		int count = 0;
		//不存在时创建新用户并插入
		if(existUser==null){
			//1.像用户表新增用户
			existUser = new UserInfo();
			existUser.setLoginCode(mobilePhone+"_"+RandomUtil.generateString2(3));
			existUser.setPassword(MD5Encrypt.encryptByMD5(password));
			existUser.setRoleId(RoleInfoEnum.STUDENT.getRoleId());
			existUser.setRegisterDate(new Date().getTime());
			existUser.setDisableFlag(0);
			existUser.setUserName(userName);
			existUser.setMobilePhone(mobilePhone);
			count = userDao.insert(existUser);
			
			if(count == 1){
				//往会员用户中间表插数据
				UserMemberInfo memberInfo = new UserMemberInfo();
				memberInfo.setUserId(existUser.getId());
				memberInfo.setMembershipFlag(1);
				memberInfo.setStartDate(new Date().getTime());
//				memberInfo.setEndDate(DateUtil.dateTimeAddYears(System.currentTimeMillis(),1));//有效期 ，福卡激活续费是增加一年的
				memberInfo.setEndDate(DateUtil.dateTimeAddDays(System.currentTimeMillis(), existCard.getDays()));
				memberInfo.setGradeId(38);//默认小学一年级
				memberDao.insert(memberInfo);
			}
			
		}else {
			//更新用户数据
            existUser.setPassword(MD5Encrypt.encryptByMD5(password));
            existUser.setUserName(userName);
			existUser.setMobilePhone(mobilePhone);
			count = userDao.updateById(existUser);
			
			int row = 0 ;
			//1.根据mobilePhone查出来的useId查询 user_member_info 
			UserMemberInfo openIdUserMemInfo = memberDao.selectByUserId(existUser.getId());
			if (openIdUserMemInfo == null) {
				openIdUserMemInfo = new UserMemberInfo();
				openIdUserMemInfo.setUserId(existUser.getId());
				openIdUserMemInfo.setMembershipFlag(1);
				openIdUserMemInfo.setStartDate(new Date().getTime());
				openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddDays(System.currentTimeMillis(),existCard.getDays()));//有效期 ，福卡激活续费是增加一年的
				openIdUserMemInfo.setGradeId(38);//默认小学一年级
				openIdUserMemInfo.setDisableFlag(0);
				row = memberDao.insert(openIdUserMemInfo);
				startTime = new Timestamp(openIdUserMemInfo.getStartDate());
				endTime = new Timestamp(openIdUserMemInfo.getEndDate());
			}else {//之前在会员表有数据，以第一条记录为主
				if (openIdUserMemInfo.getMembershipFlag().intValue() == 1) { //是会员
					//Long addTime = openIdUserMemInfo.getEndDate() - openIdUserMemInfo.getStartDate();
					if (openIdUserMemInfo.getEndDate() > System.currentTimeMillis() ) {//有效期是大于当前时间的
//						openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddYears(openIdUserMemInfo.getEndDate(),1));
						startTime = new Timestamp(openIdUserMemInfo.getEndDate());
						openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddDays(openIdUserMemInfo.getEndDate(),existCard.getDays()));//有效期 ，福卡激活续费是增加一年的
					}else{//当前日期大于endDate(正常情况是不会有这种状况的)
						//openIdUserMemInfo.setEndDate(openIdUserMemInfo.getEndDate());
//						openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddYears(System.currentTimeMillis(),1));
						startTime = new Timestamp(System.currentTimeMillis());
						openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddDays(System.currentTimeMillis(),existCard.getDays()));//有效期 ，福卡激活续费是增加一年的
					}
					endTime = new Timestamp(openIdUserMemInfo.getEndDate());
					row = memberDao.updateById(openIdUserMemInfo);
				}else{//曾为vip
//					openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddYears(System.currentTimeMillis(),1));
					openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddDays(System.currentTimeMillis(),existCard.getDays()));//有效期 ，福卡激活续费是增加一年的
					openIdUserMemInfo.setMembershipFlag(1);//设置为会员
					row = memberDao.updateById(openIdUserMemInfo);
					startTime = new Timestamp(System.currentTimeMillis());
					endTime = new Timestamp(openIdUserMemInfo.getEndDate());
				}
			}
			
			if(row == 1){
				//标注已激活卡
				existCard.setUserId(existUser.getId());
				existCard.setActivationStatus(1);
				existCard.setActivationDate(new Date().getTime());
				salesCardDao.updateSalesCard(existCard);
				
				//发送微信通知
				if(StringUtils.isNotBlank(existUser.getWeixinOpenid())){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					WeChatUtil.sendWechatTemplateMessageVip( existUser.getId().toString()
							, existUser.getUserName(), existUser.getMobilePhone(), sdf.format(openIdUserMemInfo.getEndDate())
							, WxConsts.PUBLIC_DOMAIN + "/index.html?from=weClasses/weClasses.html", existUser.getWeixinOpenid());
					
				}
				
				//发送激活成功短信
				SMSSendDto activationSms=new SMSSendDto();
				activationSms.setRecNum(mobilePhone);
				activationSms.setName("365家长课堂会员");
				activationSms.setCode(mobilePhone);
				sendActivationSMS(activationSms);
				
				//新增我的消息记录
				MessageInfo messageInfo = new MessageInfo();
				messageInfo.setTitle("会员开通通知");
				messageInfo.setContent("恭喜！您已成功开通1年365家长课堂会员");
				messageInfo.setSendTime(new Date());
				messageInfo.setSenderId(1);
				messageInfo.setUserId(existUser.getId());
				messageInfo.setReadTag(0);
				messageInfo.setMsgModule(1);//会员开通成功通知
				messageInfo.setStartTime(startTime);
				messageInfo.setEndTime(endTime);
				messageInfoDao.insert(messageInfo);
				
				//充值并开通会员
				UserBalancePayment payment = new UserBalancePayment();
				payment.setName(existCard.getSalesCardName());
				payment.setStatusId(2);
				payment.setMoney((float)existCard.getDays());
				payment.setUserId(existUser.getId());
				payment.setCode(existCard.getActivationCode());
				payment.setOrderTime(new Date());
				payment.setCompleteTime(new Date());
				payment.setPaymentMethod("card");
				payment.setTypeId(3);
				paymentDao.insertCardOrder(payment);
				
				IntegralInfo intetral = IntegralUtil.setIntegral(existUser.getId()
						, IntegralEnum.BUY_FUKA.getScore() * (365 / existCard.getDays())
						, IntegralEnum.BUY_FUKA.getTypeDesc()
						, IntegralEnum.BUY_FUKA.getTypeId()
						, existUser.getId());
				
				map.put("err_code", "301");
				map.put("err_msg", "您已成功激活福卡");
				map.put("userInfo",existUser);
			}else {
				map.put("err_code", 302);
				map.put("err_msg", "会员充值失败");
			}
		}
				
		return map;
	}

	@Override
	public Map<String, Object> txActivateFuCardByOpenId(String openId,
			String mobilePhone, String validcode, String fuCardCode,Integer typeId) {
		Map<String, Object> map = new HashMap<String, Object>();
		//
		if (StringUtils.isNotBlank(mobilePhone) && StringUtils.isNotBlank(validcode)) {
			SMSSendInfo smsSendInfo = new SMSSendInfo();
			smsSendInfo.setRecNum(mobilePhone);
			smsSendInfo.setSendCode(validcode);
//			smsSendInfo.setSmsCode(SMSTemplate.getTemplateID(typeId));
//			smsSendInfo.setSmsCode("SMS_16440022");
			//校验验证码
			SMSSendInfo smsSendInfoDB = smsSendInfoDao.validateSMSCode(smsSendInfo);
			if (smsSendInfoDB == null) {
				map.put("err_code", "101");
				map.put("err_msg", "您输入的短信验证码有误!");
				return map;
			}
			if (smsSendInfoDB.getSmsSendTime().getTime() + 600000 < new Date()
					.getTime()) {
				map.put("err_code", "102");
				map.put("err_msg", "您输入的短信验证码已过期，请重发!");
				return map;
			}
		} else {
			map.put("err_code", "401");
			map.put("err_msg", "输入的手机号码或验证码有误");
			return map;
		}
		if (StringUtils.isBlank(fuCardCode)) {
			map.put("err_code", "203");
			map.put("err_msg", "您输入的激活密码有误!");
			return map;
		}
		//查询激活卡
		SalesCardInfo existCard = salesCardDao.queryByActivationCode(fuCardCode);
		if (existCard == null || ! fuCardCode.equalsIgnoreCase(existCard.getActivationCode())) {
			map.put("err_code", "203");
			map.put("err_msg", "您输入的激活密码有误!");
			return map;
		}
		if (existCard.getActivationStatus().intValue()==1) {
			map.put("err_code", "201");
			map.put("err_msg", "该卡已被激活!");
			return map;
		} 
		if (existCard.getExpiryDate()<new Date().getTime() || existCard.getDisableFlag() ==1) {
			map.put("err_code", "202");
			map.put("err_msg", "该卡已失效!");
			return map;
		}
		//通过微信openid查询数据
		UserInfo openIdUser = userDao.queryByWeixinOpenid(openId);
		//不存在时创建新用户并插入
		Timestamp startTime= null;
		Timestamp endTime= null;
		if(openIdUser==null){
			map.put("err_code", 305);
			map.put("err_msg", "openId查询无数据");
			return map;
		}
		//通过手机号查询用户数据
		UserInfo mobileUserInfo = userDao.queryByMobilePhone(mobilePhone);
		if (mobileUserInfo !=null) {//该手机号码为老用户
			if (StringUtils.isNotBlank(mobileUserInfo.getWeixinOpenid()) && !openId.equals(mobileUserInfo.getWeixinOpenid())) {
				map.put("err_code", "306");
				map.put("err_msg", "该手机号码已被其他账户绑定");
				return map;
			}
		}
		//更新 用户数据
		UserInfo existUser = null;
		if (mobileUserInfo == null ) {//手机没被使用，直接绑定
			openIdUser.setMobilePhone(mobilePhone);
			userDao.updateById(openIdUser);
			
			existUser = openIdUser;
		}else {//上面已经做了绑定其他账户的处理，所以这里如果mobileUserInfo.openid不为空则mobileUserInfo 和existUser为同一条数据,如果openid为空，使用手机的老用户数据
			openIdUser.setDisableFlag(1);//作废新数据
			userDao.updateById(openIdUser);
			if (StringUtils.isBlank(mobileUserInfo.getWeixinOpenid())) {//实现绑定
				mobileUserInfo.setWeixinOpenid(openId);
				userDao.updateById(mobileUserInfo);
			}
			
			existUser = mobileUserInfo;
		}
		int row = 0 ;
		
		
		//type = 0 vip福卡; type = 1 课程包激活
		if(existCard.getType().equals(0)){
			//1.根据openId查出来的useId查询 user_member_info 
			UserMemberInfo openIdUserMemInfo = memberDao.selectByUserId(existUser.getId());
			if (openIdUserMemInfo == null) {
				openIdUserMemInfo = new UserMemberInfo();
				openIdUserMemInfo.setUserId(existUser.getId());
				openIdUserMemInfo.setMembershipFlag(1);
				openIdUserMemInfo.setStartDate(new Date().getTime());
				startTime = new Timestamp(openIdUserMemInfo.getStartDate());
				if(existCard.getDays() != null ){
					openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddDays(System.currentTimeMillis(), existCard.getDays()));
				}else{
					openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddYears(System.currentTimeMillis(),1));//有效期 ，福卡激活续费是增加一年的
				}
				endTime = new Timestamp(openIdUserMemInfo.getEndDate());
				openIdUserMemInfo.setGradeId(38);//默认小学一年级
				openIdUserMemInfo.setDisableFlag(0);
				row = memberDao.insert(openIdUserMemInfo);
			}else {//之前在会员表有数据，以第一条记录为主
				if (openIdUserMemInfo.getMembershipFlag().intValue() == 1) { //是会员
					//Long addTime = openIdUserMemInfo.getEndDate() - openIdUserMemInfo.getStartDate();
					if (openIdUserMemInfo.getEndDate() > System.currentTimeMillis() ) {//有效期是大于当前时间的
//						openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddYears(openIdUserMemInfo.getEndDate(),1));
						startTime = new Timestamp(openIdUserMemInfo.getEndDate());
						if(existCard.getDays() != null ){
							openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddDays(openIdUserMemInfo.getEndDate(), existCard.getDays()));
						}else{
							openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddYears(openIdUserMemInfo.getEndDate(),1));//有效期 ，福卡激活续费是增加一年的
						}
						endTime = new Timestamp(openIdUserMemInfo.getEndDate());
					}else{//当前日期大于endDate(正常情况是不会有这种状况的)
						//openIdUserMemInfo.setEndDate(openIdUserMemInfo.getEndDate());
//						openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddYears(System.currentTimeMillis(),1));
						startTime = new Timestamp(System.currentTimeMillis());
						if(existCard.getDays() != null ){
							openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddDays(System.currentTimeMillis(), existCard.getDays()));
						}else{
							//默认一年吧
							openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddYears(System.currentTimeMillis(),1));//有效期 ，福卡激活续费是增加一年的
						}
						endTime = new Timestamp(openIdUserMemInfo.getEndDate());
					}
					row = memberDao.updateById(openIdUserMemInfo);
				}else{//曾为vip
//					openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddYears(System.currentTimeMillis(),1));
					startTime = new Timestamp(System.currentTimeMillis());
					if(existCard.getDays() != null ){
						openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddDays(System.currentTimeMillis(), existCard.getDays()));
					}else{
						openIdUserMemInfo.setEndDate(DateUtil.dateTimeAddYears(System.currentTimeMillis(),1));//有效期 ，福卡激活续费是增加一年的
					}
					endTime = new Timestamp(openIdUserMemInfo.getEndDate());
					openIdUserMemInfo.setMembershipFlag(1);//设置为会员
					row = memberDao.updateById(openIdUserMemInfo);
				}
			}
			if(row == 1){
				//标注已激活卡
				existCard.setUserId(existUser.getId());
				existCard.setActivationStatus(1);
				existCard.setActivationDate(new Date().getTime());
				salesCardDao.updateSalesCard(existCard);
				
				//发送激活成功短信
				/*SMSSendDto activationSms = new SMSSendDto();
				activationSms.setRecNum(mobilePhone);
				activationSms.setName("365家长课堂会员");
				activationSms.setCode(mobilePhone);
				sendActivationSMS(activationSms);*/
				//发送微信通知
				if(StringUtils.isNotBlank(existUser.getWeixinOpenid())){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					WeChatUtil.sendWechatTemplateMessageVip( existUser.getId().toString()
							, existUser.getUserName(), existUser.getMobilePhone(), sdf.format(openIdUserMemInfo.getEndDate())
							, WxConsts.PUBLIC_DOMAIN + "/index.html?from=weClasses/weClasses.html", existUser.getWeixinOpenid());
					
				}
				//新增我的消息记录
				MessageInfo messageInfo = new MessageInfo();
				messageInfo.setTitle("会员开通通知");
				messageInfo.setContent("恭喜！您已成功开通1年365家长课堂会员");
				messageInfo.setSendTime(new Date());
				messageInfo.setSenderId(1);
				messageInfo.setUserId(existUser.getId());
				messageInfo.setReadTag(0);
				messageInfo.setMsgModule(1);//会员开通成功通知
				messageInfo.setStartTime(startTime);
				messageInfo.setEndTime(endTime);
				messageInfoDao.insert(messageInfo);
				
				//添加付款订单记录
				UserBalancePayment payment = new UserBalancePayment();
				payment.setName(existCard.getSalesCardName());
				payment.setStatusId(2);
				payment.setMoney((float)existCard.getDays());
				payment.setUserId(existUser.getId());
				payment.setCode(existCard.getActivationCode());
				payment.setOrderTime(new Date());
				payment.setCompleteTime(new Date());
				payment.setPaymentMethod("card");
				payment.setTypeId(3);
				paymentDao.insertCardOrder(payment);
				
				//激活福卡 ，获得积分
				IntegralInfo intetral = IntegralUtil.setIntegral(existUser.getId()
						, IntegralEnum.BUY_FUKA.getScore() *( existCard.getDays() / 365)
						, IntegralEnum.BUY_FUKA.getTypeDesc()
						, IntegralEnum.BUY_FUKA.getTypeId()
						, payment.getId());
				
				map.put("err_code", "301");
				map.put("err_msg", "您已成功激活福卡");
				map.put("userInfo",existUser);
			}else {
				map.put("err_code", 302);
				map.put("err_msg", "会员充值失败");
			}
		}else if(existCard.getType().equals(1)){
			int add_vip_years = 1 ;
			//查询 课程包vip
			CoursePackageVip paramVip = new CoursePackageVip();
			paramVip.setUserId(existUser.getId());
			paramVip.setCoursePackageId(existCard.getCoursePackageId());
			paramVip.setDisableFlag(0);
			CoursePackageVip vip = coursePackageVipDao.selectByUserIdAndCoursepackageId(paramVip);
			if(null == vip){//第一次购买
				vip = new CoursePackageVip();
				vip.setCoursePackageId(existCard.getCoursePackageId());
				vip.setUserId(existUser.getId());
				vip.setCreateTime(new Timestamp(System.currentTimeMillis()));
				vip.setDisableFlag(0);
				vip.setIsVipStatus(1);
				vip.setExpireTime(DateUtil.dateAddYears(vip.getCreateTime(),add_vip_years));//添加有效期
                startTime = new Timestamp(vip.getCreateTime().getTime());
                endTime = new Timestamp(vip.getExpireTime().getTime());
                row = coursePackageVipDao.insert(vip);
			}else{//续费
				vip.setIsVipStatus(1);
				if(vip.getExpireTime().getTime() - System.currentTimeMillis() > 0){//现在还没有过期，续有效期
                    startTime = new Timestamp(vip.getExpireTime().getTime());
                    vip.setExpireTime(DateUtil.dateAddYears(vip.getExpireTime(),add_vip_years));
				}else{//期限时间已经过了，则用当前时间去设置
                    startTime = new Timestamp(System.currentTimeMillis());
                    vip.setExpireTime(DateUtil.dateAddYears(new Date(),add_vip_years));
				}
                endTime = new Timestamp(vip.getExpireTime().getTime());
                row = coursePackageVipDao.updateById(vip);
			}
			CoursePackageInfoDTO vo = new CoursePackageInfoDTO();
			vo.setId(existCard.getCoursePackageId());
			vo.setUserId(existUser.getId());
			CoursePackageInfo coursePackageInfo = coursePackageInfoDao.selectById(vo);
			//课程包购买成功，新增一条我的消息
			MessageInfo messageInfo = new MessageInfo();
			messageInfo.setTitle("课程兑换成功");
			messageInfo.setContent("您已成功兑换课程包【" + coursePackageInfo.getCoursePackageName() + "】，现在开始抓紧时间学习吧！不然"+ DateUtil.dateToString(vip.getExpireTime(),DateUtil.YEAR_MONTH_DAY) +"就要过期啦");
			messageInfo.setSendTime(new Date());
			messageInfo.setSenderId(1);
			messageInfo.setUserId(existUser.getId());
			messageInfo.setReadTag(0);
			messageInfo.setMsgModule(4);//会员开通成功通知
			messageInfo.setCostId(coursePackageInfo.getId());
            messageInfo.setStartTime(startTime);
            messageInfo.setEndTime(endTime);
            messageInfoDao.insert(messageInfo);
            
            
            //激活成功后,添加缓存  格式如(key:"user_video_vip_3173" value:"8,17,23")
            List<CoursePackageInfoDTO> list = coursePackageInfoDao.selectVideoListById(coursePackageInfo);
            String vids = redisPool.get(GlobalConstant.USER_VIDEO_VIP + existUser.getId()); //用户拥有观看权限的视频 ("8,17,23")
            if (StringUtils.isBlank(vids)) {
                vids = "";
            }
            for (CoursePackageInfoDTO coursePackageInfoDTO : list) {
                //如果用户没有该单节微课的观看权限,就往缓存的value后追加
				if (!RedisUtil.isVideoVip(existUser.getId(), coursePackageInfoDTO.getVideoId())) {
					vids += (coursePackageInfoDTO.getVideoId() + ",");
				}
			}
            redisPool.set(GlobalConstant.USER_VIDEO_VIP + existUser.getId(), vids);
			
			//修改福卡激活状态
			existCard.setUserId(existUser.getId());
			existCard.setActivationStatus(1);
			existCard.setActivationDate(new Date().getTime());
			salesCardDao.updateSalesCard(existCard);
            
          //添加付款订单记录
			UserBalancePayment payment = new UserBalancePayment();
			payment.setName(existCard.getSalesCardName());
			payment.setStatusId(2);
			payment.setMoney((float)existCard.getDays());
			payment.setUserId(existUser.getId());
			payment.setCode(existCard.getActivationCode());
			payment.setOrderTime(new Date());
			payment.setCompleteTime(new Date());
			payment.setPaymentMethod("card");
			payment.setTypeId(3);
			paymentDao.insertCardOrder(payment);
			
			map.put("err_code", "301");
			map.put("err_msg", "您已成功激活");
			map.put("userInfo",existUser);
		}
		
		return map;
	}

    @Override
    public Map<String, Object> txActivateSaleCardPC(String userName, String mobilePhone,
                                                    String password, String validcode, String fuCardCode, int typeId) {
        Map<String, Object> map = new HashMap<String, Object>();
        //
        Timestamp startTime = null;
        Timestamp endTime = null;
        if (StringUtils.isNotBlank(mobilePhone) && StringUtils.isNotBlank(validcode)) {
            SMSSendInfo smsSendInfo = new SMSSendInfo();
            smsSendInfo.setRecNum(mobilePhone);
            smsSendInfo.setSendCode(validcode);
            smsSendInfo.setSmsCode(SMSTemplate.getTemplateID(typeId));
            //校验验证码
            SMSSendInfo smsSendInfoDB = smsSendInfoDao.validateSMSCode(smsSendInfo);
            if (smsSendInfoDB == null) {
                map.put("err_code", "101");
                map.put("err_msg", "您输入的短信验证码有误!");
            } else if (smsSendInfoDB.getSmsSendTime().getTime() + 600000 < new Date()
                    .getTime()) {
                map.put("err_code", "102");
                map.put("err_msg", "您输入的短信验证码已过期，请重发!");
            } else {
                if (StringUtils.isNotBlank(fuCardCode)) {
                    //查询激活卡
                    SalesCardInfo existCard = salesCardDao.queryByActivationCode(fuCardCode);
                    if (existCard != null && (existCard.getActivationCode()).equalsIgnoreCase(fuCardCode)) {
                        if (existCard.getActivationStatus().intValue() == 1) {
                            map.put("err_code", "201");
                            map.put("err_msg", "该卡已被激活!");
                            return map;
                        } else if (existCard.getExpiryDate() < new Date().getTime() || existCard.getDisableFlag() == 1) {
                            map.put("err_code", "202");
                            map.put("err_msg", "该卡已失效!");
                            return map;
                        }
                        UserInfo existUser = userDao.queryByMobilePhone(mobilePhone);
                        //不存在时创建新用户并插入
                        if (existUser == null) {
                            //1.像用户表新增用户
                            existUser = new UserInfo();
                            existUser.setLoginCode(mobilePhone + "_" + RandomUtil.generateString2(3));
                            existUser.setPassword(MD5Encrypt.encryptByMD5(password));
                            existUser.setRoleId(RoleInfoEnum.STUDENT.getRoleId());
                            existUser.setRegisterDate(new Date().getTime());
                            existUser.setDisableFlag(0);
                            existUser.setUserName(userName);
                            existUser.setMobilePhone(mobilePhone);
                            userDao.insertSelective(existUser);
                            existUser = userDao.queryByMobilePhone(mobilePhone);

                            //往会员用户中间表插数据
                            UserMemberInfo memberInfo = new UserMemberInfo();
                            memberInfo.setUserId(existUser.getId());
                            memberInfo.setMembershipFlag(1);
                            memberInfo.setStartDate(new Date().getTime());
//                            memberInfo.setEndDate(DateUtil.dateTimeAddYears(System.currentTimeMillis(), 1));//有效期 ，福卡激活续费是增加一年的
                            memberInfo.setEndDate(DateUtil.dateTimeAddDays(System.currentTimeMillis(), existCard.getDays()));
                            memberInfo.setGradeId(38);//默认小学一年级
                            memberInfo.setDisableFlag(0);
                            memberDao.insert(memberInfo);
                        } else {
                            //更新用户数据
                            existUser.setUserName(userName);
                            existUser.setMobilePhone(mobilePhone);
                            userDao.updateById(existUser);

                            UserBalancePayment payment = new UserBalancePayment();
                            payment.setUserId(existUser.getId());
                            List<UserBalancePayment> existPays = paymentDao.queryHadPaymentByUserId(payment);
                            if (existPays == null || existPays.size() == 0) {
                                //已注册，但没购买过会员套餐,往会员用户中间表插数据
                                UserMemberInfo memberInfo = new UserMemberInfo();
                                memberInfo.setUserId(existUser.getId());
                                memberInfo.setMembershipFlag(1);
                                memberInfo.setStartDate(new Date().getTime());
//                                memberInfo.setEndDate(DateUtil.dateTimeAddYears(System.currentTimeMillis(), 1));//有效期 ，福卡激活续费是增加一年的
                                memberInfo.setEndDate(DateUtil.dateTimeAddDays(System.currentTimeMillis(), existCard.getDays()));
                                memberInfo.setGradeId(38);//默认小学一年级
                                memberInfo.setDisableFlag(0);
                                memberDao.insert(memberInfo);
                            } else {
                                //vip
                                UserMemberInfo memberInfo = new UserMemberInfo();
                                memberInfo.setUserId(existUser.getId());
                                List<UserMemberInfo> list = memberDao.selectListByUserId(memberInfo);
                                if (null != list && list.size() > 0) { //之前是会员，有记录
                                    memberInfo = list.get(0);//查询是查处有效期最新的一条
                                    //如果有效期比当前时间大，则，使用有效期时间加一年，否则用当前时间加一年，并把开始时间改成当前时间
                                    if (memberInfo.getEndDate() - System.currentTimeMillis() > 0) {
                                    	startTime = new Timestamp(memberInfo.getEndDate());
                                    	memberInfo.setEndDate(DateUtil.dateTimeAddDays(memberInfo.getEndDate(), existCard.getDays()));
                                    } else {
                                    	memberInfo.setEndDate(DateUtil.dateTimeAddDays(System.currentTimeMillis(), existCard.getDays()));
                                        memberInfo.setStartDate(System.currentTimeMillis());
                                        startTime = new Timestamp(memberInfo.getStartDate());
                                    }
                                    endTime = new Timestamp(memberInfo.getEndDate());
                                    memberInfo.setMembershipFlag(1);
                                    memberInfo.setDisableFlag(0);
                                    memberDao.updateById(memberInfo);
                                } else {
                                    memberInfo.setUserId(existUser.getId());
                                    memberInfo.setMembershipFlag(1);
                                    memberInfo.setStartDate(new Date().getTime());
//                                    memberInfo.setEndDate(DateUtil.dateTimeAddYears(System.currentTimeMillis(), 1));//有效期 ，福卡激活续费是增加一年的
                                    memberInfo.setEndDate(DateUtil.dateTimeAddDays(System.currentTimeMillis(), existCard.getDays()));
                                    memberInfo.setGradeId(38);//默认小学一年级
                                    memberInfo.setDisableFlag(0);
                                    memberDao.insert(memberInfo);
                                    startTime = new Timestamp(memberInfo.getStartDate());
                                    endTime = new Timestamp(memberInfo.getEndDate());
                                }
                            }
                        }

                        //充值并开通会员
                        UserBalancePayment payment = new UserBalancePayment();
                        payment.setName(existCard.getSalesCardName());
                        payment.setStatusId(2);
                        payment.setMoney((float)existCard.getDays());
                        payment.setUserId(existUser.getId());
                        payment.setCode(existCard.getActivationCode());
                        payment.setOrderTime(new Date());
                        payment.setCompleteTime(new Date());
                        payment.setPaymentMethod("card");
                        payment.setTypeId(3);
                        int con = paymentDao.insertCardOrder(payment);
                        if (con > 0) {
                            //标注已激活卡
                            existCard.setUserId(existUser.getId());
                            existCard.setActivationStatus(1);
                            existCard.setActivationDate(new Date().getTime());
                            salesCardDao.updateSalesCard(existCard);

                            //发送激活成功短信
                            SMSSendDto activationSms = new SMSSendDto();
                            activationSms.setRecNum(smsSendInfo.getRecNum());
                            activationSms.setName("365家长课堂会员");
                            activationSms.setCode(smsSendInfo.getRecNum());
                            sendActivationSMS(activationSms);

                            //新增我的消息记录
                            MessageInfo messageInfo = new MessageInfo();
                            messageInfo.setTitle("会员开通通知");
                            messageInfo.setContent("恭喜！您已成功开通1年365家长课堂会员");
                            messageInfo.setSendTime(new Date());
                            messageInfo.setSenderId(1);
                            messageInfo.setUserId(existUser.getId());
                            messageInfo.setReadTag(0);
                            messageInfo.setMsgModule(1);//会员开通成功通知
                            messageInfo.setStartTime(startTime);
                            messageInfo.setEndTime(endTime);
                            messageInfoDao.insert(messageInfo);

                            map.put("err_code", "301");
                            map.put("err_msg", "您已成功激活福卡");
                            map.put("userInfo", existUser);
                        } else {
                            map.put("err_code", 302);
                            map.put("err_msg", "会员充值失败");
                        }

                    } else {
                        map.put("err_code", "203");
                        map.put("err_msg", "您输入的激活密码有误!");
                    }
                } else {
                    map.put("err_code", "203");
                    map.put("err_msg", "您输入的激活密码有误!");
                }
            }
        } else {
            map.put("err_code", "401");
            map.put("err_msg", "输入的手机号码或验证码有误");
        }
        return map;
    }

	@Override
	public Object getTotal(SalesCardInfo salesCardInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
        log.debug("=salesCardInfo.getUserName()==>" + salesCardInfo.getUserName());
        log.debug("=salesCardInfo.getUserName()==>" + salesCardInfo.getUserName());
        int totalCount = salesCardDao.getTotalCardCount(salesCardInfo);
		map.put("totalCount", totalCount);//总福卡数
		map.put("totalPrice", 365*totalCount);//总福卡价值
		salesCardInfo.setActivationStatus(1);
		int totalActivation = salesCardDao.getTotalCardCount(salesCardInfo);
		map.put("totalActivation",totalActivation );//总激活数
		map.put("activationPrice", 365*totalActivation); //总激活价值
		return map;
	}
	
	@Override
	public Object exportExl(SalesCardInfo salesCardInfo, HttpServletResponse response,HttpSession session){
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (StringUtils.isNotBlank(salesCardInfo.getStartTimeString())) {
			salesCardInfo.setStartTime(DateUtil.stringToLong(salesCardInfo.getStartTimeString(), DateUtil.FULL_DATE));
		}
		if (StringUtils.isNotBlank(salesCardInfo.getEndTimeString())) {
			salesCardInfo.setEndTime(DateUtil.stringToLong(salesCardInfo.getEndTimeString(), DateUtil.FULL_DATE));
		}
		List<SalesCardInfo> dataset = salesCardDao.queryCardByPage(salesCardInfo);
		if (dataset == null || dataset.size()==0) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");
			return map;
		}
		
		try {
			ExcelUtil.writeExcel(response, "福卡"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", dataset, SalesCardInfo.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}

	@Override
	public synchronized Object generateSingleCode(SalesCardInfo info, Map<String, Object> map) {
		if(StringUtils.isNotBlank(info.getDayString())){
			info.setDayString(info.getDayString() + "_day");
		}
		int days = 0;
		switch (info.getDayString()) {
		case "seven_day":
			days = 7;
			break;
		case "twenty_day":
			days = 20;
			break;
		case "thirty_day":
			days = 30;
			break;
		case "forty_day":
			days = 40;
			break;
		case "sixty_day":
			days = 60;
			break;
		case "ninety_day":
			days = 90;
		}
		
		if(days != 0){
			//判断是否领取过免费
			SalesCardInfo exist = salesCardDao.hasGetFree(info);
			//存在且有效，直接反馈
			if(exist != null){
				if(exist.getEndTime() < System.currentTimeMillis()){
					exist.setEndTime(DateUtil.dateTimeAddYears(System.currentTimeMillis(), 1));
					int row = salesCardDao.updateSalesCard(exist);
					if(row == 1){
						map.put("err_code", ResponseCode.SUCCESS.getCode());
						map.put("err_msg", ResponseCode.SUCCESS.getDesc());
						map.put("code", exist.getActivationCode());
					}
				}
				if(exist.getActivationStatus() == 1){
					map.put("err_code", -2);
					map.put("err_msg", "你已经领取过");
				}
			}else{
				//生成
				ArrayList<SalesCardInfo> list = generateCard(8, 1, DateUtil.dateTimeAddYears(System.currentTimeMillis(), 1), days, "免费领取");
				if(null !=list && list.size() > 0){
					int userId = info.getUserId();
					info = list.get(0);
					info.setUserId(userId);
					info.setIsFree(1);
					info.setAddDate(System.currentTimeMillis());
					info.setActivationStatus(0);
					info.setDisableFlag(0);
					int row = salesCardDao.insert(info);
					if(row == 1){
						map.put("err_code", ResponseCode.SUCCESS.getCode());
						map.put("err_msg", ResponseCode.SUCCESS.getDesc());
						map.put("code", info.getActivationCode());
					}
				}
			}
		}else{
			map.put("err_code", ResponseCode.ERROR_ARGS.getCode());
			map.put("err_msg", ResponseCode.ERROR_ARGS.getDesc());
			
		}
		return map;
	}
	
}
